package com.etlmaster.executor.steps.mail;

import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.etlmaster.executor.Step;
import com.etlmaster.executor.StepMeta;
import com.etlmaster.executor.annotation.StepInstruction;
import com.etlmaster.executor.utils.StepState;

/**
 * @author Wugf
 * @date 2016-03-08
 */
@StepInstruction("sendMail")
public class SendMailStep extends Step {
	private SendMailStepMeta meta;
	
	public SendMailStep(StepMeta meta) {
		super(meta);
		this.meta = (SendMailStepMeta) meta;
		// TODO Auto-generated constructor stub
	}

	@Override
	protected int handle() {

		MyAuthenticator authenticator = null;
		Properties pro = meta.getProperties();
		if (meta.isValidate()) {
			// 如果需要身份认证，则创建一个密码验证器
			authenticator = new MyAuthenticator(meta.getUserName(),
					meta.getPassword());
		} else {
			meta.log("ERROR","邮箱验证失败");
		}
		// 根据邮件会话属性和密码验证器构造一个发送邮件的session
		Session sendMailSession = Session
				.getDefaultInstance(pro, authenticator);
		try {
			
			Message mailMessage = new MimeMessage(sendMailSession);
			
			Address from = new InternetAddress(meta.getFromAddress());
			
			mailMessage.setFrom(from);
			
			String[] to = meta.getToAddress().split(",");
			InternetAddress[] address = new InternetAddress[to.length];
			for (int i = 0; i < address.length; i++) {
				address[i] = new InternetAddress(to[i]);
				//isNameAdressFormat(address[i].getAddress());
			}

			mailMessage.setRecipients(Message.RecipientType.TO, address);

			if (meta.getToAddresscc() != null
					&& meta.getToAddresscc().length() > 0) {
				String[] tocc = meta.getToAddresscc().split(",");
				InternetAddress[] addresscc = new InternetAddress[tocc.length];
				for (int i = 0; i < addresscc.length; i++) {
					addresscc[i] = new InternetAddress(tocc[i]);
					//isNameAdressFormat(address[i].getAddress());
				}
				mailMessage.setRecipients(Message.RecipientType.CC, addresscc); // 此处为非密送，若要密送将Message.RecipientType.CC改为Message.RecipientType.BCC
			}
			mailMessage.setSubject(meta.getSubject());

			mailMessage.setSentDate(new Date());

			Multipart mp = new MimeMultipart();

			MimeBodyPart mbp = new MimeBodyPart();

			
			if (meta.isHtml()) { 
				mbp.setContent(
						"你好：<br/>	"
								+ meta.getContent()
								+ "<td><div style='line-height:40px;height:40px'></div><p style='line-height:24px;font-size:12px;color:#979797;font-family:'宋体''>此邮件为测试邮件，请勿回复！</p></td>",
						"text/html;charset= " + meta.getCharset());
			} else {
				mbp.setText(meta.getContent() + meta.getSuffix());
			}
			mp.addBodyPart(mbp);

			/*
			 * if (mailInfo.getFiles() != null && mailInfo.getFiles().length >
			 * 0) { // 判断是佛有附件 // 存在附件就将附件全部加入到BodyPart for (File file :
			 * mailInfo.getFiles()) { mbp = new MimeBodyPart(); FileDataSource
			 * fds = new FileDataSource(file); // 得到数据源 mbp.setDataHandler(new
			 * DataHandler(fds)); // 得到附件本身并至入BodyPart
			 * mbp.setFileName(MimeUtility.encodeText(fds.getName())); //
			 * 得到文件名转码后同样至入BodyPart mp.addBodyPart(mbp); } }
			 */
			// Multipart加入到信件
			mailMessage.setContent(mp);

			// 发送邮件
			Transport.send(mailMessage, mailMessage.getAllRecipients());

			meta.log("INFO","邮件发送成功");

			return StepState.RUNNING_SUCCESSED;
		} catch (MessagingException ex) {

			meta.log("ERROR","发件人邮箱地址或密码有误，请重新检查！{}",ex.getMessage());
		}
		meta.log("INFO","邮件发送失败，请仔细检查相关设置是否有误！");
		return StepState.RUNNING_FAILED;

	}

	public boolean isNameAdressFormat(String email) {
		boolean isExist = false;

		Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}");
		Matcher m = p.matcher(email);
		boolean b = m.matches();
		if (b) {
			isExist = true;
		} else {
			meta.log("INFO","{}不是有效的邮件地址", email);
			System.exit(1);
		}
		return isExist;
	}

	@Override
	public boolean stop() {
		// TODO Auto-generated method stub
		return false;
	}
}